// 拍照图片质量设置
const {db, Op, QueryTypes} = require("../models/db");
const tool = require("../tools/tool");
const xe = require("xe-utils");
const pageParams = require("../tools/cols");
const getUploadToken = require("qiniu");
const {exec} = require("child_process");
const router = require('koa-router')();
//
router.post('/common/del', async ctx => {
    let ids = ctx.request.body.ids;
    let mod = ctx.request.body.mod;
    if(!mod) return ctx.err('未找到删除模型')
    if(!ids) return ctx.err('请选择要删除的数据')
    let soft = ctx.request.body.soft;
    let isTree = ctx.request.body?.isTree;
    let attrs = db.models[mod].getAttributes()
    if (isTree) {
        // 找出code 摸查子分类 并删除
        for(let id in ids) {
            let codeModel = await db.models[mod].findOne({
                where: {
                    id: ids[id]
                }
            })
            if(codeModel) {
                await db.models[mod].destroy({
                    where: {
                        code: {
                            [Op.like]: codeModel.code +'%'
                        }
                    }
                })
            }
        }
        ctx.suc('已删除 ' + ids.length + ' 条记录')
    }
    else {
        let where = {
            id: {
                [Op.in]: ids
            },
        }
        for(let i in attrs) {
            if (i === 'tenantId') {
                where.tenantId = ctx.user.tenantId
            }
        }
        if(soft) {
            let updata = {}
            for(let i in attrs) {
                if(i === 'dt') updata.dt = tool.getTime()
                if(i === 'dtime') updata.dtime = tool.getTime()
                if(i === 'dby') updata.dby = ctx.user.id
                if(i === 'isDel') updata.isDel = 1
            }
            if(!xe.isEmpty(updata)) {
                await db.transaction(async t => {
                    await db.models[mod].update(updata,
                        { where: where },{transaction: t}
                    )
                },)
            }
        }
        else {
            await db.transaction(async t => {
                await db.models[mod].destroy({
                    where: where
                },{transaction: t})
            })
        }
        ctx.suc('已删除 ' + ids.length + ' 条记录')
    }
})
router.post('/common/save', async ctx => {
    return await tool.save(ctx)
})

router.post('/common/doSort', async ctx => {
    let formData = ctx.request.body.formData;
    let mod = ctx.request.body.mod;
    if(mod) {
        formData.map( async row =>{
            await db.models[mod].update({sort: row.sort}, {
                where: {
                    id: row.id
                }
            })
        })
    }
    ctx.suc('')
})
// 执行sql语句
router.post('/common/doSql', async ctx => {
    let sql = ctx.request.body.sql
    if(sql) {
        sql = sql.replaceAll('$uid', ctx.user.id)
        sql = sql.replaceAll('${tid}', ctx.user.tenantId)
        let list = await db.query(sql, {type: QueryTypes.SELECT} )
        return ctx.suc('', list)
    }
    else {
        return ctx.err('没有查询方法')
    }
})
// 下拉数据
router.post('/common/dropdown', async ctx => {
    try {
        let cat = ctx.request.body.cat
        let keyWord = ctx.request.body.keyWord
        let id = ctx.request.body.id?ctx.request.body.id:''
        let uid = ctx.user.id
        let tid = ctx.user.tenantId
        if(cat === 'unit') {
            if(id) {
                let list = await db.query(`select name from unit where name='${id}'`,{type: QueryTypes.SELECT})
                return ctx.suc('', list)
            }
            else {
                let list = await db.query(`select name id,name from unit order by sort`,{type: QueryTypes.SELECT})
                return ctx.suc('', list)
            }
        }
        if (cat === 'dept') {
            let sql = `select b.id,b.name,b.pid from admin_data_dept a inner join dept b on a.deptId=b.id and a.selfId=${uid} where 1=1 `
            if(ctx.user.allData) {
                sql = `select id,name,pid from dept where tenantId=${tid} `
            }
            if(keyWord) {
                sql += ` and (b.name like '${keyWord}' or b.pinYin like '${keyWord}') `
            }
            let ret = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', ret)
        }
        if (cat === 'sales') {
            let sql = `select id,name from admin where tenantId=${tid} `
            let auth = tool.authSql(ctx)
            if(auth) {
                sql += ` and id in (${auth}) `
            }
            if(keyWord) {
                sql += ` and (name like '%${keyWord}%' or pinYin like '%${keyWord}%') `
            }
            let ret = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', ret)
        }
        if (cat === 'srSubject') {
            // 收入科目
            let sql = ''
            if(ctx.user.isCard === 0) {
                sql = `select id,code,concat(code,name) name from category where tenantId=${tid} and typeNumber='subject' and pid in(select id from category where typeNumber='subject' and tenantId=${tid} and name ='其他业务收入')`
            }
            else {
                sql = `
                select id,code,concat(code,name) name from category where tenantId=${tid} and typeNumber='subject' and  isDel=0   and name ='营业外收入'  
                select id, code,concat(code,'_其他业务收入_',name) name from category where tenantId=${tid} and typeNumber='subject' and  isDel=0 
                and pid in (select id from category where typeNumber='subject' and tenantId=${tid} and name ='其他业务收入'  ) `;
            }
            if (keyWord) {
                sql += ` and (name like '%${keyWord}%' or code like '%${keyWord}%' or pinYin like '%${keyWord}%') `;
            }
            sql += " order by code asc";
            let lists = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', lists);
        }
         if (cat === 'contactList') {            // 下拉商品 不带库存
            sql = `select top 80 id,code,name,linkName,linkMobile,address from contact where tenantId=${tid} `
            if (keyWord) {
                sql += ` and (name like '%${keyWord}%' or pinYin like '%${keyWord}%' or code like '%${keyWord}%' or linkMobile like '%${keyWord}%' or linkName like '%${keyWord}%' )`;
            }
            let ret = await db.query(sql, {type: QueryTypes.SELECT}) 
            let arr = []
            ret.map(row => {
                arr.push({
                    id: row.id,
                    name: row.name,
                    suffix: row.address,
                    linkMobile: row.linkMobile,
                    linkName: row.linkName,
                    address: row.address,
                })
            })
            
            return ctx.suc('', arr)
        }
        if (cat === 'zcSubject') {
            // 支出科目
            let sql = ''
            if(ctx.user.isCard === 0) {
                sql = `select id,code,concat(code,name) name from category where tenantId=${tid} and typeNumber='subject' and pid in(select id from category where typeNumber='subject' and tenantId=${tid} and name ='其他业务支出')`
            }
            else {
                sql = `SELECT * from ( 
                select id,code,concat(code,name) name,pinYin,isDel from category where tenantId=${tid} and typeNumber='subject' and  isDel=0   and name ='营业外支出' union all  
                select id, code, concat(code,'_销售费用_',name) name,pinYin,isDel  from category where tenantId=${tid} and typeNumber='subject' and pid in (select id from category where typeNumber='subject' and tenantId=${tid} and name ='销售费用'  ) union all  
                select id, code, concat(code,'_管理费用_',name) name,pinYin,isDel  from category where tenantId=${tid} and typeNumber='subject' and pid in (select id from category where typeNumber='subject' and tenantId=${tid} and name ='管理费用'  ) union all   
                select id, code, concat(code,'_财务费用_',name) name,pinYin,isDel  from category where tenantId=${tid} and typeNumber='subject' and pid in (select id from category where typeNumber='subject' and tenantId=${tid} and name ='财务费用'  )  
                UNION ALL  select id, code, concat(code,'_其他业务支出_',name) name,pinYin,isDel  from category where tenantId=${tid} and typeNumber='subject' and pid in (select id from category where typeNumber='subject' and tenantId=${tid} and name ='其他业务支出'  )  
                 ) a where isDel=0 `
            }
            if (keyWord) {
                sql += ` and (name like '%${keyWord}%' or code like '%${keyWord}%' or pinYin like '%${keyWord}%') `;
            }
            sql += " order by code asc";
            let lists = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', lists);
        }
        if (cat === 'accountList') {
            let sql = ''
            if(ctx.user.isCard === 0) {
                sql = `SELECT id,code,name from category where tenantId=${tid} and typeNumber='subject' and pid in(SELECT id from category where tenantId=${tid} and typeNumber='subject' and name = '银行存款')`
            }
            else {
               sql = `select id,code, name from category where pid in (SELECT id from category where tenantId=${tid} and typeNumber='subject' and name = '库存现金')  and isDel=0  `
                if (keyWord) {
                    sql += ` and (name like '%${keyWord}%' or code like '%${keyWord}%') `;
                }
                sql += ` union all  select id,code, name from category where pid in (SELECT id from category where tenantId=${tid} and typeNumber='subject' and name = '银行存款') and isDel=0 `;
            }
            if (keyWord) {
                sql += ` and (name like '%${keyWord}%' or code like '%${keyWord}%') `;
            }
            let lists = db.select(sql);
            return ctx.suc('', lists);
        }
        if (cat === 'deliver') {
            let sql = `select a.id,a.name from admin a inner join role b on a.roleId=b.id and a.tenantId=${tid} and b.name in('送货员','驾驶员') `
            let ret = await db.query(sql, {type: QueryTypes.SELECT})
            return ctx.suc('', ret)
        }
        let where = {
            tenantId: tid,
        }
        if(id) {
            where.id = id
        }
        else {
            let attrs = db.models[cat].getAttributes()
            let or = {}
            for(let i in attrs) {
                if(i === 'isDel') {
                    where.isDel = 0
                }
                if(keyWord) {
                    if(i === 'pinYin') {
                        or.pinYin = {
                            [Op.like]: `%${keyWord}%`
                        }
                    }
                    if(i === 'name') {
                        or.name = {
                            [Op.like]: `%${keyWord}%`
                        }
                    }
                }
            }
            if(!tool.xe.isEmpty(or)) {
                where[Op.or] = or
            }
        }
        let list = await db.models[cat].findAll({
            where ,
            attributes: ['id', 'name'],
            limit: 30
        })

        return ctx.suc('', list)
    }
    catch (e) {
        console.log('err', e)
        return ctx.err('没有记录')
    }
})
// 七牛下载地址
router.post('/common/getDownUrl', async ctx => {
    let fileName = ctx.request.body.fileName
    let salesName = ctx.user.name
    let url = tool.getPicUrl(fileName, salesName, true)
    return ctx.suc('', url)
})
router.post('/common/getOne', async ctx => {
    let sql = ctx.request.body.sql
    if(sql) {
        let list = await db.query(sql, {type: QueryTypes.SELECT, plain: true} )
        return ctx.suc('', list)
    }
    else {
        return ctx.err('没有查询方法')
    }
})
// 页面通用参数加载
router.post('/common/getPageParams', async ctx => {
    let page = ctx.request.body.page;
    let params = await db.query(` select * from form_cust where page= '${page}' `, {type: QueryTypes.SELECT, plain: true})
    let fieldsArr = [
        {
            field: 'id',
            title: 'ID',
            isKey: true,
            visible: false,
            add: false,
            edit: false
        },
        {
            field: 'seq',
            type: 'seq',
            title: '#',
            width: 60,
            align: 'center',
            visible: true,
            fixed: 'left'
        },
        {
            field: 'checked',
            type: 'checkbox',
            title: '',
            width: 40,
            fixed: 'left',
            visible: true,
            align: 'center'
        },
    ]

    let ctimeField = "{field: 'ctime', title: '创建时间',excelOut:true,sortable:true, width: 105 }";
    let utimeField = "{field: 'utime', title: '更新时间',excelOut:true,sortable:true,  width: 105 }";
    let dtimeField = "{field: 'dtime', title: '删除时间',excelOut:true,sortable:true,   width: 105 }";
    let fileName = params.name; // 导出的文件名称
    let cols = JSON.parse(params.fields); // 查询。编辑的字段
    cols.map(item => fieldsArr.push(item));
    let toolbarstr = params.toolbar; // toolbar
    let contextmenustr = params.contextmenu; // contextmenu
    let btns = [
        // {
        //     code: 'refresh',
        //     name: '刷新',
        //     prefixIcon: 'fa fa-refresh',
        //     title: '重置所有条件并刷新当前页',
        //     disabled: false
        // },
        {
            code: 'search',
            name: '查询',
            prefixIcon: 'fa fa-search',
            title: '高级搜索',
            disabled: false
        },
        {
            code: 'auth',
            name: '权限',
            prefixIcon: 'fa fa-user-o',
            title: '编辑权限',
            disabled: false
        },
        {
            code: 'setPwd',
            name: '密码',
            prefixIcon: 'fa fa-user-o',
            title: '设置密码',
            disabled: false
        },
        {
            code: 'add',
            name: '新增',
            prefixIcon: 'fa fa-plus',
            title: '新增 1 条数据',
            disabled: false
        },
        {
            code: 'edit',
            name: '编辑',
            prefixIcon: 'fa fa-edit',
            title: '编辑 1 条数据',
            disabled: false
        },
        {
            code: 'accounted',
            name: '记账',
            prefixIcon: 'fa fa-rmb',
            title: '记账',
            disabled: false
        },
        {
            code: 'del',
            name: '删除',
            prefixIcon: 'fa fa-trash',
            title: '删除选中条目',
            disabled: false
        },
        {
            code: 'copy',
            name: '复制',
            prefixIcon: 'fa fa-copy',
            title: '复制单元格内容',
            disabled: false
        },
        {
            code: 'import',
            name: '导入',
            prefixIcon: 'fa fa-upload',
            title: '导入数据',
            disabled: false
        },
        {
            code: 'export',
            name: '导出',
            prefixIcon: 'fa fa-download',
            title: '导出数据',
            disabled: false
        },
        {
            code: 'print',
            name: '打印',
            prefixIcon: 'fa fa-print',
            title: '打印页面内容',
            disabled: false
        },
        {
            code: 'columns',
            name: '选列',
            prefixIcon: 'fa fa-columns',
            title: '选择要显示的列',
            disabled: false
        },
        {
            code: 'close',
            name: '关闭',
            prefixIcon: 'fa fa-close',
            title: '关闭',
            disabled: false
        },
        {
            code: 'lock',
            name: '锁屏',
            prefixIcon: 'fa fa-lock',
            title: '离开并锁定屏幕',
            disabled: false
        },
    ]
    let btnList = []

    for (let btn in btns) {
        if (toolbarstr.indexOf(btn.code) != -1) {
            btnList.add(btn)
        }
    }
    let contextmenu = []
    for (let btn in btns) {
        // if (contextmenustr.indexOf(btn.code) != -1) {
        //     contextmenu.add(btn)
        // }
    }
    for (let it in fieldsArr) {
        if (it.field === 'beginDate') {
            it.default = tool.getDay('', -15)
        }
        if (it.field === 'endDate') {
            it.default = tool.getDay()
        }
    }
    return ctx.suc('', {
        btnList,
        contextmenu,
        columns: fieldsArr,
        params: params
    })
})
router.post('/common/getParams', async ctx => {
    ctx.suc('', pageParams(ctx, tool))
})
// 打印地址
router.post('/common/getPrintUrl', async ctx => {
    return ctx.suc('', 'https://download.sanzhiyun.cn/app/print.zip')
})
// 生成七牛上传token
router.post('/common/getUploadToken', async ctx => {
    const accessKey = 'Qv_OXaTQUf1Gi2dvH1Qe77wtLOdMuNMSPCUXzK6j';
    const secretKey = 'pEVQBydHGAZFEmG98ai6UJLL_TsdP-4dd0CxSXNF';
    const mac = new getUploadToken.auth.digest.Mac(accessKey, secretKey);
    const options = {
        scope: 'szcloud',
    };
    const putPolicy = new getUploadToken.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    return ctx.suc('', uploadToken)
})
router.post('/common/list', async ctx => {
    let sql = ctx.request.body.sql
    if (sql) {
        return await tool.page(ctx, sql)
    }
    return  ctx.err('没有查询参数')
})
router.post('/common/listByMod', async ctx => {
    let mod = ctx.request.body.mod
    let order = ctx.request.body.order
    if (mod) {
        let options = {}
        if(order) {
            // sort,desc|s,asc
            let sort = order.split('|')
            let ord = []
            for (let i = 0; i < sort.length; i++) {
                if(sort[i]) {
                    let inn = sort[i].split(',')
                    if(inn.length === 2) {
                        ord.push(inn)
                    }
                }
            }
            if(ord.length > 0)
                options.order = ord
        }
        let list = await db.models[mod].findAll(options)
        return ctx.suc('', list)
    }
    return  ctx.suc('', [])
})
router.post('/common/photoSets', async ctx => {
    return ctx.suc('', {
        targetWidth: 1200,
        targetHeight: 1200,
        quality: 90
    })
})
// 发送验证码
router.post('/common/sendSms', async ctx => {
    let mobile = tool.xe.toString(ctx.request.body.mobile);
    let user = await db.models['admin'].findOne({
        where: {
            username: mobile
        }
    })
    if(!user) {
        user = await db.models['admin'].findOne({
            where: {
                mobile: mobile
            }
        })
        if(!user) {
            return ctx.err('没有该手机号用户')
        }
    }
    let command = `curl -X POST  http://smsapi.sanzhiyun.cn/1/requestSmsCode -H "X-Bmob-Application-Id:6095550591df6bd5b252fad4012dcc90" -H "X-Bmob-REST-API-Key: 83e5bbe060ffd6d7e346919df019edb5" -d "{\\"mobilePhoneNumber\\": \\"${mobile}\\"}" -H "Content-Type: application/json"`
    let ret = await exeCurl(command)
    if(ret.stat) {
        return ctx.suc('验证码已发送')
    }
    else {
        return ctx.err(ret.msg)
    }
})
// 验证 验证码
router.post('/common/validSms', async ctx => {
    let mobile = tool.xe.toString(ctx.request.body.mobile);
    let smsId = tool.xe.toString(ctx.request.body.yzm);
    let user = await db.models['admin'].findOne({
        where: {
            username: mobile
        }
    })
    if(!user) {
        user = await db.models['admin'].findOne({
            where: {
                mobile: mobile
            }
        })
        if(!user) {
            return ctx.err('没有该手机号用户')
        }
    }
    if(mobile && smsId) {
        let command = `curl -X POST  http://smsapi.sanzhiyun.cn/1/verifySmsCode/${smsId} -H "X-Bmob-Application-Id:6095550591df6bd5b252fad4012dcc90" -H "X-Bmob-REST-API-Key: 83e5bbe060ffd6d7e346919df019edb5" -d "{\\"mobilePhoneNumber\\": \\"${mobile}\\"}" -H "Content-Type: application/json"`
        let ret = await exeCurl1(command)
        if(ret.stat) {
            // 验证码正确
            // 开始登录
            return await tool.login(user.username, user.userpwd, ctx)
        }
        else {
            return ctx.err(ret.msg)
        }
    }
    else {
        return  ctx.err('请填写验证码'+mobile)
    }
})

const exeCurl = (command) => {
    return new Promise(async (resolve, reject) => {
        exec(command,  (error, stdout, code) => {
            let obj = JSON.parse(stdout)
            if(obj.error) {
                resolve({stat: false, msg: obj.error, data: ''})
            }
            if (error !== null) {
                resolve({stat: false, msg: '发送失败', data: ''})
            }
            if (obj.smsId) {
                resolve({stat: true, msg: '', data: obj.smsId})
            } else {
                resolve({stat: false, msg: '发送失败', data: ''})
            }
        })
    })
}
const exeCurl1 = (command) => {
    return new Promise(async (resolve, reject) => {
        exec(command,  (error, stdout, code) => {
            let obj = JSON.parse(stdout)
            if(obj.error) {
                resolve({stat: false, msg: obj.error, data: ''})
            }
            if (error !== null) {
                resolve({stat: false, msg: '验证失败', data: ''})
            }
            if (obj.msg === 'ok') {
                resolve({stat: true, msg: ''})
            } else {
                resolve({stat: false, msg: '验证失败'})
            }
        })
    })
}







module.exports = router;